<template>
  <div class="login">
    <van-tabs v-model="active">
      <van-tab title="验证码登录"> 验证码登录 </van-tab>
      <van-tab title="密码登录">
        <van-form @submit="onSubmit">
          <van-field
            v-model="username"
            name="用户名"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="password"
            type="password"
            name="密码"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <van-field
            v-model="captcha"
            type="text"
            name="验证码"
            label="验证码"
            placeholder="验证码"
            :rules="[{ required: true, message: '请填写验证码' }]"
          />
          <div style="margin: 16px">
            <van-button round block type="info" native-type="submit"
              >提交</van-button
            >
          </div>
          <div v-html="url" @click="refreshCaptcha"></div>
        </van-form>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { getCaptcha, login } from '@/api/user'
export default {
  data () {
    return {
      active: 1,
      username: '13428273363',
      password: '123456',
      captcha: 'aaaa',
      url: '',
      name: null,
      params: {}
    }
  },
  created () {
    // 页面一上来就应该有验证码
    this.refreshCaptcha()
  },
  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被验证前调用
    // 不能获取组件实例 `this` ！
    // 因为当守卫执行时，组件实例还没被创建！
    console.log(from)
    next(vm => {
    // 通过 `vm` 访问组件实例
      vm.name = from.name
      vm.params = from.params
    })
  },
  methods: {
    async onSubmit (values) {
      //  发起登录请求
      const res = await login({
        captcha: this.captcha,
        password: this.password,
        userName: this.username
      })
      if (res.data.success_code === 200) {
        localStorage.setItem('token', 'Bearer ' + res.data.token)
        // 跳转到对应的页面 如果你从其他页面跳过来登录，登录成功以后需要回到那个页面。如果你是直接进入的登录，应该直接跳到首页
        if (this.name) {
          this.$router.push({ name: this.name, params: this.params })
        } else {
          this.$router.push('/')
        }
      }
    },
    async refreshCaptcha () {
      const res = await getCaptcha()
      this.url = res.data
    }
  }
}
</script>

<style>
</style>
